<?php
/**
 * Module used for application authentication
 *
 * @author André Silva
 */
class Authentication implements IModule {
	const SESSION_USER = '_cerberus_authentication_user';
	const SESSION_REDIRECT_PAGE = '_cerberus_authentication_redirect_page';

	private static $user;
	private static $loginPage;

	public static function start($args) {
		import('cerberus.controller.ProtectedController');
		self::$user = self::getUser();
		self::$loginPage = $args['loginPage'];
	}

	public static function finish() {

	}

	/**
	 * Get the controller used for login
	 * @return string
	 */
	public static function getLoginPage() {
		return self::$loginPage;
	}

	/**
	 * Register a user object as authenticated
	 * @param IUser $user
	 */
	public static function setUser($user) {
		if (!Cerberus::hasInterface(get_class($user), 'IUser')) {
			throw new Exception('Interface IUser not implement in '.$className.'');
		}
		Session::set(self::SESSION_USER, $user);
	}

	/**
	 * Get the current logged user
	 * @return IUser
	 */
	public static function getUser() {
		if (self::$user === null) {
			self::$user = Session::get(self::SESSION_USER);
		}
		return self::$user;
	}

	/**
	 * Check if exist a logged user
	 * @return boolean
	 */
	public static function isLogged() {
		return self::$user !== null;
	}

	/**
	 * Get the last accessed page before login
	 * @return string
	 */
	public static function getRedirectPage() {
		return Session::get(self::SESSION_REDIRECT_PAGE);
	}

	/**
	 * Set the current accessed page before redirect to login page
	 * @param string $param
	 */
	public static function setRedirectPage($param) {
		Session::set(self::SESSION_REDIRECT_PAGE, $param);
	}
}
?>
